package com.lh0811.forge.pserv.uacs.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lh0811.forge.dependency.basic_code.BeanHelper;
import com.lh0811.forge.dependency.basic_code.IdWorker;
import com.lh0811.forge.dependency.basic_code.encrypt.PwdUtil;
import com.lh0811.forge.dependency.basic_web.exception.CommonException;
import com.lh0811.forge.dependency.basic_web.response.ServerResponse;
import com.lh0811.forge.dependency.security.client.component.SecurityUtil;
import com.lh0811.forge.dependency.security.core.model.entity.SecurityAuthority;
import com.lh0811.forge.pserv.basic.api.api.BizNoBaseApi;
import com.lh0811.forge.pserv.uacs.api.component.data_scope.DataScope;
import com.lh0811.forge.pserv.uacs.api.constant.UacsContant;
import com.lh0811.forge.pserv.uacs.api.param.*;
import com.lh0811.forge.pserv.uacs.api.vo.UacsPlateUserQueryVo;
import com.lh0811.forge.pserv.uacs.api.vo.UacsTenantDepartmentPostQueryVo;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsPlateUserDao;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsTenantDepartmentPostDao;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsTenantPlateUserPostRefDao;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsViewTenantDepartmentUserDao;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsPlateUser;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsTenantDepartmentPost;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsTenantPlateUserPostRef;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsViewTenantDepartmentUser;
import com.lh0811.forge.pserv.uacs.server.service.PlateUserService;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlateUserServiceImpl implements PlateUserService {

    @Resource
    private UacsPlateUserDao uacsPlateUserDao;

    @Resource
    private UacsViewTenantDepartmentUserDao uacsViewTenantDepartmentUserDao;

    @Resource
    private BizNoBaseApi bizNoBaseApi;

    @Resource
    private UacsTenantPlateUserPostRefDao uacsTenantPlateUserPostRefDao;

    @Resource
    private UacsTenantDepartmentPostDao uacsTenantDepartmentPostDao;

    @Override
    @DataScope
    public PageInfo<UacsPlateUserQueryVo> plateUserQueryPage(UacsPlateUserQueryPageParam param) throws Exception {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<UacsViewTenantDepartmentUser> uacsPlateUserList = uacsViewTenantDepartmentUserDao.lambdaQuery()
                .like(StringUtils.isNotBlank(param.getRealName()), UacsViewTenantDepartmentUser::getRealName, param.getRealName())
                .like(StringUtils.isNotBlank(param.getPhone()), UacsViewTenantDepartmentUser::getPhone, param.getPageNum())
                .eq(ObjectUtils.isNotEmpty(param.getGender()), UacsViewTenantDepartmentUser::getGender, param.getGender())
                .eq(ObjectUtils.isNotEmpty(param.getRealNameFlag()), UacsViewTenantDepartmentUser::getRealNameFlag, param.getRealNameFlag())
                .eq(ObjectUtils.isNotEmpty(param.getActiveFlag()), UacsViewTenantDepartmentUser::getActiveFlag, param.getActiveFlag())
                .eq(ObjectUtils.isNotEmpty(param.getWriteOffFlag()), UacsViewTenantDepartmentUser::getWriteOffFlag, param.getWriteOffFlag())
                .orderByDesc(UacsViewTenantDepartmentUser::getCreateTime)
                .list();
        PageInfo uacsPlateUserPageInfo = new PageInfo<>(uacsPlateUserList);
        PageHelper.clearPage();
        uacsPlateUserPageInfo.setList(BeanHelper.copyList(uacsPlateUserPageInfo.getList(), UacsPlateUserQueryVo.class));
        return uacsPlateUserPageInfo;
    }

    @Override
    @DataScope
    public List<UacsPlateUserQueryVo> plateUserQueryList(UacsPlateUserQueryListParam param) throws Exception {
        List<UacsViewTenantDepartmentUser> plateUsers = uacsViewTenantDepartmentUserDao.lambdaQuery()
                .like(StringUtils.isNotBlank(param.getRealName()), UacsViewTenantDepartmentUser::getRealName, param.getRealName())
                .like(StringUtils.isNotBlank(param.getPhone()), UacsViewTenantDepartmentUser::getPhone, param.getPhone())
                .eq(ObjectUtils.isNotEmpty(param.getGender()), UacsViewTenantDepartmentUser::getGender, param.getGender())
                .eq(ObjectUtils.isNotEmpty(param.getRealNameFlag()), UacsViewTenantDepartmentUser::getRealNameFlag, param.getRealNameFlag())
                .eq(ObjectUtils.isNotEmpty(param.getActiveFlag()), UacsViewTenantDepartmentUser::getActiveFlag, param.getActiveFlag())
                .eq(ObjectUtils.isNotEmpty(param.getWriteOffFlag()), UacsViewTenantDepartmentUser::getWriteOffFlag, param.getWriteOffFlag())
                .orderByDesc(UacsViewTenantDepartmentUser::getCreateTime)
                .list();
        return BeanHelper.copyList(plateUsers, UacsPlateUserQueryVo.class);
    }

    @Override
    public void plateUserCreate(UacsPlateUserCreateParam param) throws Exception {
        SecurityAuthority securityAuthority = SecurityUtil.getSecurityAuthority();
        if (!StringUtils.equals(param.getPassword(), param.getRepwd())) {
            throw CommonException.create(ServerResponse.createByError("两次输入密码不一致"));
        }

        if (uacsPlateUserDao.lambdaQuery().eq(UacsPlateUser::getPhone, param.getPhone()).exists()) {
            throw CommonException.create(ServerResponse.createByError("手机号已存在"));
        }

        UacsPlateUser uacsPlateUser = new UacsPlateUser();
        uacsPlateUser.setId(IdWorker.nextId()); // 主键
        uacsPlateUser.setPlateUserNo(bizNoBaseApi.getNextNumByBizType(UacsContant.BizNoType.平台用户编号.getBizType())); // 平台用户编号
        uacsPlateUser.setNickName(param.getNickName()); // 昵称
        uacsPlateUser.setRealName(param.getRealName()); // 真实姓名
        uacsPlateUser.setPhone(param.getPhone()); // 手机号
        String gensalt = PwdUtil.gensalt();
        String pwd = PwdUtil.hashPassword(param.getPassword(), gensalt);
        uacsPlateUser.setPassword(pwd); // 密码
        uacsPlateUser.setSalt(gensalt); // 密码盐
        uacsPlateUser.setBirthday(param.getBirthday()); // 生日
        uacsPlateUser.setGender(param.getGender()); // 性别： 00-保密 01-男 02-女
        uacsPlateUser.setRealNameFlag(Boolean.FALSE); // 是否实名认证
        uacsPlateUser.setLastLoginTime(new Date()); // 最后一次登录时间
        uacsPlateUser.setActiveFlag(param.getActiveFlag()); // 是否可用
        uacsPlateUser.setWriteOffFlag(param.getWriteOffFlag()); // 是否注销
        uacsPlateUser.setNotes(param.getNotes()); // 备注
        uacsPlateUser.setCreateTime(new Date()); // 创建时间
        uacsPlateUser.setCreateBy(Long.valueOf(securityAuthority.getUserId())); // 创建人
        uacsPlateUserDao.save(uacsPlateUser);
    }

    @Override
    public void plateUserUpdate(UacsPlateUserUpdateParam param) throws Exception {
        SecurityAuthority securityAuthority = SecurityUtil.getSecurityAuthority();
        UacsPlateUser uacsPlateUser = uacsPlateUserDao.getById(param.getId());
        if (ObjectUtils.isEmpty(uacsPlateUser)) {
            throw CommonException.create(ServerResponse.createByError("用户信息不存在"));
        }

//        if (StringUtils.isNotBlank(param.getPassword())) {
//            if (!StringUtils.equals(param.getPassword(), param.getRepwd())) {
//                throw CommonException.create(ServerResponse.createByError("两次输入密码不一致"));
//            }
//        }

        if (StringUtils.isNotBlank(param.getPhone()) && !StringUtils.equals(param.getPhone(), uacsPlateUser.getPhone())) {
            if (uacsPlateUserDao.lambdaQuery().eq(UacsPlateUser::getPhone, param.getPhone()).exists()) {
                throw CommonException.create(ServerResponse.createByError("手机号已存在"));
            }
        }

        UacsPlateUser updateInfo = BeanHelper.copyBean(param, UacsPlateUser.class);
//        updateInfo.setPassword(PwdUtil.hashPassword(param.getPassword(), uacsPlateUser.getSalt()));
        updateInfo.setUpdateBy(Long.valueOf(securityAuthority.getUserId()));
        updateInfo.setUpdateTime(new Date());
        updateInfo.setId(uacsPlateUser.getId());
        uacsPlateUserDao.updateById(updateInfo);
    }

    @Override
    public void plateUserDelete(Long id) throws Exception {
        SecurityAuthority securityAuthority = SecurityUtil.getSecurityAuthority();
        UacsPlateUser uacsPlateUser = uacsPlateUserDao.getById(id);
        if (ObjectUtils.isEmpty(uacsPlateUser)) {
            throw CommonException.create(ServerResponse.createByError("用户信息不存在"));
        }
        // 判断用是否存在岗位信息
        List<UacsTenantPlateUserPostRef> list = uacsTenantPlateUserPostRefDao.lambdaQuery().eq(UacsTenantPlateUserPostRef::getPlateUserId, uacsPlateUser.getId()).list();
        if (CollectionUtils.isNotEmpty(list)) {
            throw CommonException.create(ServerResponse.createByError("用户已绑定岗位不可删除"));
        }
        uacsPlateUserDao.removeById(id);
    }

    @Override
    public void plateUserTenantPostRefSave(UacsPlateUserPostRefSaveParam param) throws Exception {
        SecurityAuthority securityAuthority = SecurityUtil.getSecurityAuthority();
        UacsPlateUser uacsPlateUser = uacsPlateUserDao.getById(param.getUserId());
        if (ObjectUtils.isEmpty(uacsPlateUser)) {
            throw CommonException.create(ServerResponse.createByError("用户信息不存在"));
        }

        // 移除岗位关联
        List<UacsTenantPlateUserPostRef> plateUserPostRefList = uacsTenantPlateUserPostRefDao.lambdaQuery().eq(UacsTenantPlateUserPostRef::getPlateUserId, param.getUserId()).list();
        if (CollectionUtils.isNotEmpty(plateUserPostRefList)) {
            uacsTenantPlateUserPostRefDao.removeByIds(plateUserPostRefList.stream().map(ele -> ele.getId()).collect(Collectors.toList()));
        }

        // 保存新的岗位关联关系
        if (CollectionUtils.isNotEmpty(param.getPostIdList())) {
            List<UacsTenantPlateUserPostRef> newPlateUserPostRefList = Lists.newArrayList();
            for (Long postId : param.getPostIdList()) {
                UacsTenantDepartmentPost departmentPost = uacsTenantDepartmentPostDao.getById(postId);
                if (ObjectUtils.isEmpty(departmentPost)) {
                    throw CommonException.create(ServerResponse.createByError("岗位信息不存在"));
                }

                UacsTenantPlateUserPostRef plateUserPostRef = new UacsTenantPlateUserPostRef();
                plateUserPostRef.setId(IdWorker.nextId()); // 主键
                plateUserPostRef.setPlateUserId(uacsPlateUser.getId()); // 平台用户id
                plateUserPostRef.setPlateUserNo(uacsPlateUser.getPlateUserNo()); // 平台用户编号
                plateUserPostRef.setTenantId(departmentPost.getTenantId()); // 租户id
                plateUserPostRef.setTenantNo(departmentPost.getTenantNo()); // 租户编号
                plateUserPostRef.setTenantName(departmentPost.getTenantName()); // 租户名称
                plateUserPostRef.setDepartmentId(departmentPost.getDepartmentId()); // 组织机构id
                plateUserPostRef.setDepartmentNo(departmentPost.getDepartmentNo()); // 组织机构编号
                plateUserPostRef.setDepartmentName(departmentPost.getDepartmentName()); // 组织机构名称
                plateUserPostRef.setPostId(departmentPost.getId()); // 岗位id
                plateUserPostRef.setPostNo(departmentPost.getPostNo()); // 岗位编号
                plateUserPostRef.setPostName(departmentPost.getPostName()); // 岗位名称
                plateUserPostRef.setCreateTime(new Date()); // 创建时间
                plateUserPostRef.setCreateBy(Long.valueOf(securityAuthority.getUserId())); // 创建人
                newPlateUserPostRefList.add(plateUserPostRef);
            }
            uacsTenantPlateUserPostRefDao.saveBatch(newPlateUserPostRefList);
        }
    }

    // 获取用户绑定的岗位
    @Override
    public List<UacsTenantDepartmentPostQueryVo> getUserBuildingPostList(Long userId) throws Exception {
        SecurityAuthority securityAuthority = SecurityUtil.getSecurityAuthority();
        List<UacsTenantPlateUserPostRef> postRefs = uacsTenantPlateUserPostRefDao.lambdaQuery().eq(UacsTenantPlateUserPostRef::getPlateUserId, userId).list();
        if (CollectionUtils.isEmpty(postRefs)) {
            return Lists.newArrayList();
        }
        List<UacsTenantDepartmentPost> tenantDepartmentPostList = uacsTenantDepartmentPostDao.listByIds(postRefs.stream().map(ele -> ele.getPostId()).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(tenantDepartmentPostList)) {
            return Lists.newArrayList();
        }
        return BeanHelper.copyList(tenantDepartmentPostList, UacsTenantDepartmentPostQueryVo.class);
    }


}
